package com.example.crm.service.impl;

import com.example.crm.mapper.CustomerMapper;
import com.example.crm.pojo.Customer;
import com.example.crm.service.ICustomerService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CustomerServiceImpl implements ICustomerService {
    SqlSessionFactory sqlSessionFactory;
    CustomerMapper customerMapper;
    // 每次执行测试前 要执行的代码
   {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 2. 加载SqlMapConfig.xml配置文件
       InputStream inputStream = null;
       try {
           inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
       } catch (IOException e) {
           e.printStackTrace();
       }

       // 3. 创建SqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

       SqlSession sqlSession = this.sqlSessionFactory.openSession();

       customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }

    @Override
    public List<Customer> findAll() {
        return customerMapper.selectByExample(null);
    }

    @Override
    public boolean add(Customer c) {
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        int result = customerMapper.insert(c);
        sqlSession.commit();
        return result > 0;
    }

    @Override
    public boolean deleteById(long id) {
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        int result = customerMapper.deleteByPrimaryKey(id);
        sqlSession.commit();
        return result>0;
    }

    @Override
    public Customer findById(long id) {
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        Customer customer = customerMapper.selectByPrimaryKey(id);
        return customer;
    }

    @Override
    public boolean update(Customer c) {
        SqlSession sqlSession = this.sqlSessionFactory.openSession();
        CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);
        int result = customerMapper.updateByPrimaryKey(c);
        sqlSession.commit();
        return result>0;
    }
}
